# This code is hosted on http://code.google.com/p/lenthorp/
# Freely available for use in applications, but should NOT be modified
# Email all comments to lenthorpresearch@gmail.com

import struct

class SaveSimFile():

    def __init__(self, saveFileName, times):
        # create the file
        self._fileHandle = open(saveFileName, 'wb')
        # write the times at the top
        self._nTimes = len(times) + 1
        data = struct.pack('i',self._nTimes)
        self._fileHandle.write(data)
        data = struct.pack('f',0.0)
        self._fileHandle.write(data)
        for idx in range(self._nTimes-1):
            data = struct.pack('f',times[idx])
            self._fileHandle.write(data)

    def writeSim(self, path):
        # append the sim to the file
        for idx in range(self._nTimes):
            data = struct.pack('f',path[idx])
            self._fileHandle.write(data)

    def close(self):
        self._fileHandle.close()


class LoadSimFile():

    def __init__(self, saveFileName):
        self._fileHandle = open(saveFileName,'rb')
        nTimes = self._fileHandle.read(4)
        self._nTimes = struct.unpack('i',nTimes)[0]
        self._times = [0.0 for idx in range(self._nTimes)]
        for idx in range(self._nTimes):
            data = self._fileHandle.read(4)
            self._times[idx] = struct.unpack('f',data)[0]

    def __iter__(self):
        return self
    
    def next(self):
        data = self._fileHandle.read(4)
        path = [0.0 for idx in range(self._nTimes)]
        if data == '':
            raise StopIteration()
        else:
            try:
                path[0] = struct.unpack('f',data)[0]
                for idx in range(1,self._nTimes):
                    data = self._fileHandle.read(4)
                    path[idx] = struct.unpack('f',data)[0]
                return path
            except:
                raise StopIteration()
            

    def close(self):
        self._fileHandle.close()

    def timePoints(self, index):
        return self._times[index]